package com.hotelManager.www.controller;

import com.hotelManager.www.po.*;
import com.hotelManager.www.service.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;


/**
 * 客户端控制器
 * 实现客户端所有功能
 */
public class CustomerController {
    private final UserService userService;
    private final ShopService shopService;
    private final OrderService orderService;
    private final BlacklistService blacklistService;
    private final SignInService signInService;
    private final BrowseHistoryService browseHistoryService;

    public CustomerController() {
        this.userService = new UserService();
        this.shopService = new ShopService();
        this.orderService = new OrderService();
        new RoomTypeService();
        this.blacklistService = new BlacklistService();
        this.signInService = new SignInService();
        this.browseHistoryService = new BrowseHistoryService();
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 登录成功返回用户对象，失败返回null
     */
    public User login(String username, String password) {
        return userService.loginUser(username, password);
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return 注册是否成功
     */
    public boolean register(User user) {
        return userService.registerUser(user);
    }

    /**
     * 修改个人信息
     * @param user 用户信息
     * @return 修改是否成功
     */
    public boolean updateUserInfo(User user) {
        System.out.println("[CustomerController.updateUserInfo] 开始更新用户信息 - 用户ID: " + user.getId());
        System.out.println("[CustomerController.updateUserInfo] 更新内容 - 用户名: " + user.getUsername() 
            + ", 密码: " + (user.getPassword() != null ? "已设置" : "未设置")
            + ", 角色: " + user.getRole());
        boolean result = userService.updateUserPasswordOrUsername(user);
        System.out.println("[CustomerController.updateUserInfo] 更新结果: " + (result ? "成功" : "失败"));
        return result;
    }

    /**
     * 充值
     * @param user 用户
     * @param amount 充值金额
     * @return 充值申请是否成功
     */
    public boolean recharge(User user, int amount) {
        try {
            return userService.recharge(user,amount);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查看账户余额
     * @param userId 用户ID
     * @return 用户对象
     */
    public User viewBalance(int userId) {
        try {
            User user = userService.findById(userId);
            if (user != null) {
                System.out.println("查到的用户余额为: " + user.getBalance());
                return user;// 返回完整的用户对象
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 分页模糊查询店铺，支持排序
     * @param keyword 关键词
     * @param page 页码
     * @param pageSize 每页数量
     * @param sortField 排序字段
     * @param sortOrder 排序顺序
     * @return 店铺列表和总数
     */
    public Map<String, Object> browseShops(String keyword, int page, int pageSize, String sortField, String sortOrder) {
        List<Shop> list = shopService.searchShopsWithPaginationAndSort(keyword, page, pageSize, sortField, sortOrder);
        int total = shopService.countVisibleShopsByKeyword(keyword);
        int totalPages = (int) Math.ceil((double) total / pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("totalPages", totalPages);
        result.put("page", page);
        result.put("pageSize", pageSize);
        return result;
    }

    /**
     * 根据销量排序店铺
     * @return 按销量排序的店铺列表
     */
    public List<Shop> getShopsBySalesVolume() {
        return shopService.getShopsBySalesVolume();
    }

    /**
     * 根据发布时间排序店铺
     * @return 按发布时间排序的店铺列表
     */
    public List<Shop> getShopsByTime() {
        return shopService.getShopsByTime();
    }

    /**
     * 查看历史订单
     * @param userId 用户ID
     * @return 订单列表
     */
    public List<Order> viewHistoryOrders(int userId) {
        try {
            return OrderService.getOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 订房
     * @param userId 用户ID
     * @param shopId 店铺ID
     * @param roomId 房间ID
     * @param days 入住天数
     * @return 订单对象
     */
    public Order bookRoom(int userId, int shopId, int roomId, int days) {
        try {
            System.out.println("[订房参数] userId=" + userId + ", shopId=" + shopId + ", roomId=" + roomId + ", days=" + days);
            Order order = OrderService.createOrder(userId, shopId, roomId, days);
            System.out.println("[订房结果] order=" + order);
            return order;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 退订
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 退订是否成功
     */
    public boolean cancelOrder(int userId, int orderId) {
        try {
            return orderService.cancelOrder(userId, orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 收藏店铺
     * @param userId 用户ID
     * @param shopId 店铺ID
     * @return 收藏是否成功
     */
    public boolean favoriteShop(int userId, int shopId) {
        return shopService.addFavoriteShop(userId, shopId);
    }

    /**
     * 取消收藏店铺
     * @param userId 用户ID
     * @param shopId 店铺ID
     * @return 取消收藏是否成功
     */
    public boolean unfavoriteShop(int userId, int shopId) {
        return shopService.removeFavoriteShop(userId, shopId);
    }

    /**
     * 查看收藏的店铺
     *
     * @param userId 用户ID
     * @return 收藏的店铺列表
     */
    public List<Shop> viewFavoriteShops(int userId) {
        return shopService.getFavoritesByUserId(userId);
    }

    /**
     * 搜索店铺
     * @param keyword 关键词
     * @param page 页码
     * @param pageSize 每页数量
     * @return 店铺列表
     */
    public List<Shop> searchShops(String keyword, int page, int pageSize) {
        return shopService.searchShopsWithPagination(keyword, page, pageSize);
    }

    /**
     * 每日签到
     * @param userId 用户ID
     * @return 签到是否成功
     */
    public boolean dailySignIn(int userId) {
        try {
            // 检查今日是否已签到
            if (signInService.isSignedInToday(userId)) {
                return false;
            }
            
            // 获取连续签到天数
            int consecutiveDays = signInService.getConsecutiveSignInDays(userId);
            
            // 计算获得的积分
            int points = calculateSignInPoints(consecutiveDays + 1);
            
            // 记录签到
            return signInService.recordSignIn(userId, points);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 计算签到获得的积分
     * @param consecutiveDays 连续签到天数
     * @return 获得的积分
     */
    private int calculateSignInPoints(int consecutiveDays) {
        // 基础积分
        int basePoints = 10;
        
        // 连续签到奖励
        int bonusPoints = 0;
        if (consecutiveDays > 1) {
            bonusPoints = (consecutiveDays - 1) * 2;
        }
        
        return basePoints + bonusPoints;
    }

    /**
     * 拉黑商家
     * @param userId 用户ID
     * @param shopId 店铺ID
     * @return 拉黑是否成功
     */
    public boolean blacklistShop(int userId, int shopId) throws Exception {
        System.out.println("[CustomerController.blacklistShop] 开始拉黑商家，用户ID: " + userId + ", 店铺ID: " + shopId);
        boolean result = blacklistService.addToBlacklist(userId, shopId);
        if (result) {
            System.out.println("[CustomerController.blacklistShop] 拉黑商家成功，用户ID: " + userId + ", 店铺ID: " + shopId);
        } else {
            System.err.println("[CustomerController.blacklistShop] 拉黑商家失败，用户ID: " + userId + ", 店铺ID: " + shopId);
        }
        return result;
    }

    /**
     * 查看浏览历史
     * @param userId 用户ID
     * @return 浏览历史列表
     */
    public List<BrowseHistory> viewBrowseHistory(int userId) {
        return browseHistoryService.getBrowseHistory(userId);
    }

    /**
     * 记录浏览历史
     * @param userId 用户ID
     * @param shopId 店铺ID
     * @return 记录是否成功
     */
    public boolean recordBrowseHistory(int userId, int shopId) {
        return browseHistoryService.recordBrowseHistory(userId, shopId);
    }

    /**
     * 获取店铺详情
     * @param shopId 店铺ID
     * @return 店铺对象
     */
    public Shop getShopDetail(int shopId) {
        // 使用新的方法获取包含地址和联系方式的商店信息
        Shop shop = shopService.getShopBriefById(shopId);
        if (shop != null) {
            // 更新浏览量
            shopService.updateViewCount(shopId);
        }
        return shop;
    }

    /**
     * 支付订单
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return true-支付成功，false-失败
     */
    public boolean payOrder(int userId, int orderId) {
        System.out.println("[CustomerController.payOrder] 开始处理支付 - userId: " + userId + ", orderId: " + orderId);
        try {
            // 检查订单是否存在
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                System.out.println("[CustomerController.payOrder] 订单不存在 - orderId: " + orderId);
                return false;
            }

            // 检查订单是否属于该用户
            if (order.getUserId() != userId) {
                System.out.println("[CustomerController.payOrder] 无权支付此订单 - userId: " + userId + ", orderUserId: " + order.getUserId());
                return false;
            }

            // 检查订单状态
            if (!"pending".equals(order.getStatus())) {
                System.out.println("[CustomerController.payOrder] 订单状态不是待支付 - status: " + order.getStatus());
                return false;
            }

            // 执行支付
            orderService.payOrder(userId, orderId);
            System.out.println("[CustomerController.payOrder] 支付成功 - userId: " + userId + ", orderId: " + orderId);
            return true;
        } catch (Exception e) {
            System.err.println("[CustomerController.payOrder] 支付处理异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取用户签到统计数据
     * @param userId 用户ID
     * @return 包含签到统计信息的Map
     */
    public Map<String, Object> getSignInStats(int userId) {
        Map<String, Object> stats = new HashMap<>();
        try {
            // 获取所有签到记录
            List<SignInRecord> records = signInService.getSignInRecords(userId);
            
            // 计算总签到天数
            int totalDays = records != null ? records.size() : 0;
            
            // 获取连续签到天数
            int consecutiveDays = signInService.getConsecutiveSignInDays(userId);
            
            // 计算总积分
            int totalPoints = 0;
            if (records != null) {
                for (SignInRecord record : records) {
                    totalPoints += record.getPointsEarned();
                }
            }
            
            // 组装返回数据
            stats.put("totalDays", totalDays);
            stats.put("consecutiveDays", consecutiveDays);
            stats.put("totalPoints", totalPoints);
            
            return stats;
        } catch (Exception e) {
            e.printStackTrace();
            return stats;
        }
    }

    /**
     * 获取用户签到历史记录
     * @param userId 用户ID
     * @return 签到记录列表
     */
    public List<SignInRecord> getSignInHistory(int userId) {
        try {
            return signInService.getSignInRecords(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

}
